<template>
  <div class="outer">
    <div class="breadTitle">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>用户管理</el-breadcrumb-item>
        <el-breadcrumb-item>用户列表</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="user-body">
      <div class="user-input">
        <el-input
          placeholder="请输入搜索的内容"
          v-model="queryInfo.query"
          clearable
          @clear="clearClk"
        >
          <el-button
            slot="append"
            icon="el-icon-search"
            @click="searchUser"
          ></el-button>
        </el-input>
        <el-button type="primary" @click="dialogVisible = true"
          >添加用户</el-button
        >
      </div>
      <div class="user-table">
        <el-table style="width: 100%" :data="tableData" border stripe>
          <el-table-column label="#" min-width="4%" type="index">
          </el-table-column>
          <el-table-column label="姓名" min-width="16%" prop="username">
          </el-table-column>
          <el-table-column label="邮箱" min-width="16%" prop="email">
          </el-table-column>
          <el-table-column label="电话" min-width="16%" prop="mobile">
          </el-table-column>
          <el-table-column label="角色" min-width="16%" prop="role_name">
          </el-table-column>
          <el-table-column label="状态" min-width="16%" prop="mg_state">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.mg_state"
                active-color="#13ce66"
                inactive-color="#ff4949"
                @change="userDataChanged(scope.row)"
              >
              </el-switch>
            </template>
          </el-table-column>

          <el-table-column label="操作" width="250px">
            <template slot-scope="scope">
              <el-tooltip
                class="item"
                effect="dark"
                content="修改"
                placement="top"
                ><el-button
                  type="primary"
                  icon="el-icon-edit"
                  @click="changeUserInfo(scope.row.id)"
                ></el-button
              ></el-tooltip>

              <el-tooltip
                class="item"
                effect="dark"
                content="删除"
                placement="top"
              >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  @click="delUser(scope.row.id)"
                ></el-button>
              </el-tooltip>

              <el-tooltip
                class="item"
                effect="dark"
                content="设置"
                placement="top"
              >
                <el-button
                  type="warning"
                  icon="el-icon-s-tools"
                  @click="setRoles(scope.row)"
                ></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <div class="user-footer">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :page-sizes="[1, 2, 3, 4]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :current-page="queryInfo.pagenum"
        :page-size="queryInfo.pagesize"
      >
      </el-pagination>
    </div>

    <el-dialog
      title="添加用户"
      :visible.sync="dialogVisible"
      width="50%"
      @close="formClose"
    >
      <el-form
        ref="userFromRef"
        label-width="70px"
        :rules="formRules"
        :model="addForm"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="formPrecheck">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户数据对话框 -->
    <el-dialog
      title="修改数据"
      :visible.sync="dialogVisibleUserChange"
      width="35%"
      @close="changeUserFormClosed"
    >
      <el-form
        ref="changeUserFormdata"
        :model="changeUserData"
        label-width="auto"
        :rules="changeUserRules"
      >
        <el-form-item label="用户名">
          <el-input v-model="changeUserData.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="changeUserData.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="changeUserData.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleUserChange = false">取 消</el-button>
        <el-button type="primary" @click="changeUserDataPreCheck"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <!-- 分配角色对话框 -->
    <el-dialog
      title="分配角色"
      :visible.sync="dialogRoles"
      width="50%"
      @close="setRoleClosed"
    >
      <div>
        <p>用户：{{ userInfo.username }}</p>
        <p>角色：{{ userInfo.role_name }}</p>
      </div>
      <template>
        <el-select v-model="selectedRoleId" placeholder="请选择">
          <el-option
            v-for="item in rolesList"
            :key="item.id"
            :label="item.roleName"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </template>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogRoles = false">取 消</el-button>
        <el-button type="primary" @click="saveUserInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data () {
    // 验证邮箱的规则
    var checkEmail = (rule, value, cb) => {
      // 验证邮箱的正则表达式
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (regEmail.test(value)) {
        // 合法的函数
        return cb()
      }

      cb(new Error('请输入合法的邮箱'))
    }
    // 验证手机号的规则
    var checkMobile = (rule, value, cb) => {
      // 验证手机号的正则表达式
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (regMobile.test(value)) {
        // 合法的函数
        return cb()
      }
      cb(new Error('请输入合法的手机号'))
    }
    return {
      tableData: [],
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      total: 0,
      dialogVisible: false,
      dialogVisibleUserChange: false,
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      formRules: {
        username: [
          { required: true, message: '请输入用户名称', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 16 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'change' }
        ],
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: checkMobile, trigger: 'change' }
        ]
      },
      // 修改用户数据规则
      changeUserRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 查询到的用户信息
      changeUserData: '',
      // 分配角色对话框
      dialogRoles: false,
      // 用户数据信息
      userInfo: '',
      // 用户角色信息菜单
      rolesList: [],
      // 已选中的角色ID值
      selectedRoleId: ''
    }
  },
  methods: {
    async getUserData () {
      const { data: res } = await this.$http.get('users', {
        params: this.queryInfo
      })
      if (res.meta.status !== 200) {
        return this.$message.err('获取用户列表失败！')
      }
      this.tableData = res.data.users
      this.total = res.data.total
    },
    handleSizeChange (newSize) {
      this.queryInfo.pagesize = newSize
      this.getUserData()
    },
    handleCurrentChange (newPage) {
      this.queryInfo.pagenum = newPage
      this.getUserData()
    },
    async userDataChanged (state) {
      const { data: res } = await this.$http.put(
        `users/${state.id}/state/${state.mg_state}`
      )
      if (res.meta.status !== 200) {
        state.mg_state = !state.mg_state
        return this.$message.error('更新用户状态失败！')
      } else {
        this.$message.success('更新成功！')
      }
    },
    searchUser () {
      this.getUserData()
    },
    clearClk () {
      this.queryInfo.query = ''
      this.getUserData()
    },
    // 表单重置操作
    formClose () {
      this.$refs.userFromRef.resetFields()
    },
    // 表单提交预校验
    formPrecheck () {
      // 只要有一项不符合先前定义的规则valid就返回false
      this.$refs.userFromRef.validate(async valid => {
        if (!valid) {
          this.$message.error('请填写完整的信息')
        } else {
          // 发起添加用户请求
          const { data: res } = await this.$http.post('users', this.addForm)
          if (res.meta.status !== 201) {
            this.$message.error(res.meta.msg)
          }
          this.$message.success(res.meta.msg)
          this.dialogVisible = false
          this.getUserData()
          // console.log(this.addForm)
        }
      })
    },
    // 修改用户数据按钮
    async changeUserInfo (id) {
      const { data: res } = await this.$http.get('users/' + id)
      // console.log(res)
      if (res.meta.status !== 200) {
        this.$message.error('获取用户数据失败！')
      } else {
        this.changeUserData = res.data
        console.log(res.data)
        this.$message.success('获取用户数据成功！')
        this.dialogVisibleUserChange = true
      }
    },
    // 监听修改用户对话框的关闭事件
    changeUserFormClosed () {
      this.$refs.changeUserFormdata.resetFields()
      console.log(this.$refs.changeUserFormdata)
    },
    // 修改用户信息并提交
    changeUserDataPreCheck () {
      this.$refs.changeUserFormdata.validate(async valid => {
        if (!valid) {
          this.$message.error('数据不合法！')
        } else {
          const { data: res } = await this.$http.put(
            'users/' + this.changeUserData.id,
            {
              email: this.changeUserData.email,
              mobile: this.changeUserData.mobile
            }
          )
          if (res.meta.status !== 200) {
            this.$message.error('出错了！')
          } else {
            this.getUserData()
            this.$message.success('用户信息修改成功！')
            this.dialogVisibleUserChange = false
          }
        }
      })
    },
    // 删除用户信息
    async delUser (id) {
      const confirmRes = await this.$confirm(
        '此操作将永久删除用户数据, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
      if (confirmRes === 'confirm') {
        const { data: res } = await this.$http.delete('users/' + id)
        console.log(res)
        if (res.meta.status !== 200) {
          this.$message.error(res.meta.msg)
        } else {
          this.getUserData()
          this.$message.success(res.meta.msg)
        }
      }
    },
    // 用户角色修改
    async setRoles (userInfo) {
      this.userInfo = userInfo
      // 展示对话框前获取所有角色列表
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        this.$message.error(res.meta.msg)
      } else {
        this.rolesList = res.data
        console.log(res.data)
      }
      this.dialogRoles = true
    },
    // 用户新角色提交
    async saveUserInfo () {
      if (!this.selectedRoleId) {
        return this.$message.error('请选择新的用户角色')
      }
      const { data: res } = await this.$http.put(
        `users/${this.userInfo.id}/role`,
        {
          rid: this.selectedRoleId
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
      this.dialogRoles = false
      this.getUserData()
    },
    // 监听分配角色对话框关闭
    setRoleClosed () {
      this.selectedRoleId = ''
      this.userInfo = []
    }
  },

  created () {
    this.getUserData()
  }
}
</script>
<style lang="less" scoped>
.outer {
  background-color: #fff;
}

.breadTitle {
  background-color: #cdf;
  padding-bottom: 20px;
}

.el-input {
  width: 500px;
  margin: 10px 30px 10px 10px;
}

.user-footer {
  width: 100%;
  text-align: center;
}

.el-pagination {
  padding: 15px;
}
</style>
